import {View, processColor, StyleProp, ViewStyle} from 'react-native';
import {
  LineChart,
  LineChartProps,
  LineDatasetConfig,
} from '@see_you/react-native-charts-wrapper';
import {fromJS, Map} from 'immutable';
import {
  useLayoutEffect,
  useState,
  type RefObject,
  ReactNode,
  useRef,
} from 'react';
import EmptyContent from '../EmptyContent';
import {Icon, Text, useAppTheme} from 'tsun-smart-ui';
import { hexWithOpacity } from '@/utils';
function wrapMap<T extends object>(obj: T) {
  return Map(obj);
}
function Chart({
  chartData,
  showLegend = true,
  title,
  xAxisLabels,
  dataSetsConfig,
  ref,
  leftUnit,
  highlightPerTapEnabled,
  rightUnit,
  marker,
  showFullScreen = false,
  style,
  onFullScreen,
  ...rest
}: {
  chartData: number[][];
  showLegend?: boolean;
  xAxisLabels: string[];
  title?: string[];
  leftUnit?: string | ReactNode;
  rightUnit?: string | ReactNode;
  ref?: RefObject<LineChart | null>;
  dataSetsConfig?: LineDatasetConfig[];
  marker?: string;
  highlightPerTapEnabled?: boolean;
  showFullScreen?: boolean;
  style?: StyleProp<ViewStyle>;
  onFullScreen?: () => void;
} & Omit<LineChartProps, 'data'>) {
  const theme = useAppTheme();
  const chartRef = useRef<LineChart>(null);
  const [isEmpty, setIsEmpty] = useState(false);
  useLayoutEffect(() => {
    if (!highlightPerTapEnabled) {
      (ref ?? chartRef).current?.highlights([]);
    }
  }, [highlightPerTapEnabled]);
  useLayoutEffect(() => {
    const result = chartData.every(item => {
      return item.length === 0;
    });
    setIsEmpty(result);
  }, [chartData]);
  if (isEmpty) {
    return <EmptyContent />;
  }
  const dataConfig: LineDatasetConfig = {
    color: processColor(theme.colors?.info?.primary),
    drawCircles: false,
    drawFilled: true,
    mode: 'HORIZONTAL_BEZIER',
    lineWidth: 2,
    drawHorizontalHighlightIndicator: false,
    drawVerticalHighlightIndicator: true,
    drawValues: false,
    fillGradient: {
      colors: [
        processColor(hexWithOpacity(theme.colors?.info?.primary!, 0)),
        processColor(hexWithOpacity(theme.colors?.info?.primary!, 0.4)),
      ],
      orientation: 'TOP_BOTTOM',
    },
    fillAlpha: 100,
    highlightColor: processColor(theme.colors?.neutral?.tip),
  };
  //@ts-ignore
  const flatChartData: LineChartProps['data']['dataSets'] = chartData.flatMap(
    (item, index) => {
      return [
        {
          values: item.map((item, index) => {
            return {
              y: item,
              marker: marker + xAxisLabels[index],
            };
          }),
          config: dataSetsConfig?.[index]
            ? {
                ...dataConfig,
                ...dataSetsConfig?.[index],
              }
            : dataConfig,
          label: title?.[index],
        },
      ];
    },
  );
  const DEFAULT_CONFIG = wrapMap<Omit<LineChartProps, 'data'>>({
    xAxis: {
      position: 'BOTTOM',
      textColor: processColor(theme.colors?.neutral?.secondaryTitle),
      textSize: 12,
      axisLineColor: processColor(theme.colors?.neutral?.disabled),
      gridColor: processColor(theme.colors?.background?.disabled),
      centerAxisLabels: false,
      granularity: 1,
      avoidFirstLastClipping: true,
      drawGridLines: false,
      valueFormatter: xAxisLabels,
      labelCount: 4,
    },
    yAxis: {
      left: {
        position: 'OUTSIDE_CHART',
        textColor: processColor(theme.colors?.neutral?.primary),
        textSize: 10,
        axisLineColor: processColor(theme.colors?.neutral?.disabled),
        gridColor: processColor(theme.colors?.background?.disabled),
        centerAxisLabels: false,
        labelCount: 4,
        granularity: 1,
        since: 0,
        axisMinimum: 0,
        drawAxisLine: true,
        valueFormatter: `0  `,
      },
      right: {
        enabled: false,
        position: 'OUTSIDE_CHART',
        textColor: processColor(theme.colors?.neutral?.primary),
        textSize: 10,
        axisLineColor: processColor(theme.colors?.neutral?.disabled),
        gridColor: processColor(theme.colors?.background?.disabled),
        labelCount: 5,
        granularity: 1,
        since: 0,
        axisMinimum: 0,
        drawAxisLine: true,
        valueFormatter: `0  `,
      },
    },
    marker: {
      enabled: true,
    },
  });
  const mergedConfig = DEFAULT_CONFIG.mergeDeep(fromJS(rest)).toJS();
  return (
    <View className="flex-1">
      {showFullScreen && (
        <Icon
          className=" self-end mb-3"
          name="screen"
          onPress={onFullScreen}
          size={20}
          color={theme.colors?.neutral?.secondaryTitle}></Icon>
      )}
      <View className="flex-row justify-between">
        {typeof leftUnit === 'string' ? (
          <Text
            variant="footer"
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {leftUnit}
          </Text>
        ) : (
          leftUnit
        )}
        {typeof rightUnit === 'string' ? (
          <Text
            variant="footer"
            style={{
              color: theme.colors?.neutral?.primary,
            }}>
            {rightUnit}
          </Text>
        ) : (
          rightUnit
        )}
      </View>
      <LineChart
        ref={ref ?? chartRef}
        style={[{flex: 1}, style]}
        chartDescription={{
          text: '',
        }}
        legend={{
          enabled: false,
        }}
        highlightPerTapEnabled={highlightPerTapEnabled ?? true}
        data={{
          dataSets: flatChartData,
        }}
        {...mergedConfig}
      />
    </View>
  );
}

export default Chart;
